package quadtree;

import java.util.Vector;

public class NewQuadTree<T> {

	NewQuadTreeNode<T> rootNode;
	
	public NewQuadTree(DoublePoint startCoordinates, DoubleDimension size) {
		rootNode = new NewQuadTreeNode<T>(startCoordinates, size, 0);
	}
	
	public Vector<NewQuadTreeElement<T>> queryObject(DoublePoint coordinates, DoubleDimension size) {
		return rootNode.queryObject(coordinates, size);
	}
	
	/**
	 * Add a new element to the QuadTree
	 * 
	 * @param x
	 * @param y
	 * @param element
	 */
	public void insert(int x, int y, T element) {
		insert(new DoublePoint(x, y), element);
	}
	
	public void predivide() {
		rootNode.preDivide();
	}
	
	/**
	 * Add a new element to the QuadTree
	 * 
	 * @param point
	 * @param element
	 */
	public void insert(DoublePoint point, T element) {

		// Check if the element coordinates are within bounds of the quadtree
		if (point.x > rootNode.startCoordinates.x + rootNode.bounds.width) {
			point.x = rootNode.startCoordinates.x + rootNode.bounds.width;
		}
		if (point.x < rootNode.startCoordinates.x) {
			point.x = rootNode.startCoordinates.x;
			/*throw new IndexOutOfBoundsException(
					"The x coordinate must be within bounds of ["
							+ rootNode.startCoordinates.x + "] to [" + rootNode.bounds.width + "]");*/
		}
		if (point.y > rootNode.startCoordinates.y + rootNode.bounds.height) {
			point.y = rootNode.startCoordinates.y + rootNode.bounds.height;
		}
		if (point.y < rootNode.startCoordinates.y) {
			point.y = rootNode.startCoordinates.y;
			/*throw new IndexOutOfBoundsException(
					"The y coordinate must be within bounds of ["
							+ rootNode.startCoordinates.y + "] to [" + rootNode.bounds.height + "]");*/
		}

		this.rootNode.insert(new NewQuadTreeElement<T>(point, element));
	}
	
	/**
	 * Returns the rootNode of this tree
	 * 
	 * @return
	 */
	public NewQuadTreeNode<T> getRootNode() {
		return this.rootNode;
	}

	/**
	 * Returns all elements wihtin the cell that matches the given coordinates
	 * 
	 * @param coordinates
	 * @return
	 */
	public Vector<? extends NewQuadTreeElement<T>> getElements(DoublePoint coordinates) {
		return this.rootNode.getElements(coordinates);
	}

	public void clear() {
		this.rootNode.clear();
	}
}
